<template>
  <div>
    <el-input
      placeholder="请输入手机号/邮箱/账号"
      v-model="accountForm.username"
    ></el-input>
    <el-input
      placeholder="请输入密码"
      type="password"
      v-model="accountForm.password"
    ></el-input>

    <div class="login-options">
      <el-checkbox v-model="accountForm.autoLogin">下次自动登录</el-checkbox>
      <a href="#" class="forgot-password" @click="openForgotPassword">找回密码</a>
    </div>

    <el-button type="primary" @click="loginWithPassword">账号登录</el-button>

    <!-- 找回密码弹窗 -->
    <ForgotPassword
      v-if="showForgotPassword"
      @close="closeForgotPassword"
    />
  </div>
</template>

<script>
import ForgotPassword from "@/components/ForgotPassword.vue"; // 导入 ForgotPassword 组件

export default {
  components: {
    ForgotPassword, // 注册 ForgotPassword 组件
  },
  data() {
    return {
      accountForm: {
        username: "",
        password: "",
      },
      showForgotPassword: false, // 控制找回密码弹窗显示
    };
  },
  methods: {
    openForgotPassword() {
      this.showForgotPassword = true; // 打开找回密码弹窗
    },
    closeForgotPassword() {
      this.showForgotPassword = false; // 关闭找回密码弹窗
    },
    async loginWithPassword() {
      const { username, password } = this.accountForm;

      if (!username || !password) {
        alert("请输入账号和密码！");
        return;
      }

      try {
        const response = await fetch(`/api/login/username?username=${username}&password=${password}`, {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
        });

        const result = await response.json();
        if (result.code === "200") {
          alert(`登录成功，欢迎 ${result.data.username}`);
          localStorage.setItem("token", result.data.token); // 保存 token
          localStorage.setItem("id", result.data.id); // 保存 token
          this.$router.push("/account"); // 跳转到账号页面
          this.$emit("login-success", {
            username: result.data.name,
          });
        } else {
          alert(`登录失败: ${result.message}`);
        }
      } catch (error) {
        console.error("账号登录失败:", error);
        alert("登录失败，请稍后重试！");
      }
    },
  },
};
</script>

<style scoped>
.forgot-password {
  float: right;
  cursor: pointer;
}
</style>
